package cn.dankal.flyaudio.personal

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import api.CurrentServiceFactory
import api.UserServiceFactory
import cn.dankal.basiclib.DKUserManager
import cn.dankal.basiclib.base.activity.BaseActivity
import cn.dankal.basiclib.common.camera.CamerImageBean
import cn.dankal.basiclib.common.camera.CameraHandler
import cn.dankal.basiclib.common.camera.RequestCodes
import cn.dankal.basiclib.common.qiniu.UploadListener
import cn.dankal.basiclib.pojo.UserInfoBean
import cn.dankal.basiclib.protocol.PersonalProtocol
import cn.dankal.basiclib.rx.AbstractDialogSubscriber
import cn.dankal.basiclib.template.personal.ChangeAvatar
import cn.dankal.basiclib.template.personal.ChangeAvatarImpl
import cn.dankal.basiclib.util.ToastUtils
import cn.dankal.basiclib.widget.titlebar.TitleWithAction
import cn.dankal.business.pojo.VerifyCarBean
import cn.dankal.flyaudio.R
import cn.dankal.basiclib.common.upload.ali.AliUIDisplayer
import cn.dankal.basiclib.common.upload.ali.AliUploadHelper
import cn.dankal.basiclib.pojo.UserResponseBody
import cn.dankal.basiclib.protocol.MainProtocol
import cn.dankal.basiclib.util.ImagePathUtil
import cn.dankal.basiclib.util.StringUtil
import cn.dankal.basiclib.util.UriUtils
import cn.dankal.basiclib.util.image.PicUtils
import cn.dankal.basiclib.widget.CommonDialog
import cn.dankal.basiclib.widget.TipDialog
import cn.dankal.basiclib.widget.TipDialog.Builder.ICON_TYPE_FAIL
import cn.dankal.business.pojo.LisenseBean
import cn.dankal.business.Constants
import cn.dankal.business.eventbus.MessageUpdateCarListEvent
import cn.dankal.business.pojo.ReasonBean
import cn.dankal.flyaudio.personal.brand.BrandActivity
import com.alibaba.android.arouter.facade.annotation.Route
import kotlinx.android.synthetic.main.activity_verify_driver.*
import org.greenrobot.eventbus.EventBus

@Route(path = PersonalProtocol.VERIFY)
class VerifyDriverActivity : BaseActivity() {
    var carLisense: String? = null
    var driverLisense: String? = null
    var carPic: String? = null
    var type: Int = -1
    var camera: ChangeAvatar? = null
    lateinit var builder: TipDialog.Builder
    var uploadListener: UploadListener? = null
    var mUploadHelper: AliUploadHelper? = null
    var vehicleBrandUuid: String? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_verify_driver
    }

    override fun initComponents() {

        rl_add_car_lisense.setOnClickListener {
            selectPic(Constants.TYPE_CAR_LISENSE)
        }

        rl_add_driver_lisense.setOnClickListener {
            selectPic(Constants.TYPE_DRIVER_LISENSE)

        }
        rl_add_car_pic.setOnClickListener {
            selectPic(Constants.TYPE_CAR_PIC)
        }



        camera = ChangeAvatarImpl(this, this)
        setResetState()



        uploadListener = object : UploadListener {
            override fun onSucess(localPath: String, key: String) {
                loadingDialog.dismiss()
                val dialog = builder.setIconType(TipDialog.Builder.ICON_TYPE_SUCCESS)
                        .setTipWord("上传成功")
                        .create(2000)
                dialog.show()
                dialog.dismiss()

                //                String path = PicUtil.getUrl(key);
                //                Uri uri = Uri.fromFile(tempFile);
                //                getIvHead().setImageURI(uri);


                when (type) {
                    Constants.TYPE_CAR_LISENSE -> {
                        carLisense = key
                        PicUtils.loadNormal(key, iv_car_lisense)
                    }
                    Constants.TYPE_DRIVER_LISENSE -> {
                        driverLisense = key
                        PicUtils.loadNormal(key, iv_driver_lisense)
                    }
                    else -> {
//                Constants.TYPE_CAR_PIC
                        carPic = key
                        PicUtils.loadNormal(key, iv_car_pic)
                    }
                }

            }

            override fun onUpload(percent: Double) {
//                val df = DecimalFormat("#0.00")
//                builder.setTipWord(df.format(percent * 100) + "%").showProgress()
                builder.setTipWord(percent.toString() + "%").showProgress()
            }

            override fun onError(string: String) {
                ToastUtils.showLong(string)
                loadingDialog.dismiss()
                val dialog = builder.setIconType(ICON_TYPE_FAIL)
                        .setTipWord("上传失败")
                        .create(2000)
                dialog.show()
                dialog.dismiss()
            }
        }
    }


    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        //目前target修改成了23规避适配问题
        //        https://stackoverflow.com/questions/38200282/android-os-fileuriexposedexception-file-storage-emulated-0-test-txt-exposed
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                RequestCodes.TAKE_PHOTO -> {
                    val takePath = CamerImageBean.getInstance().path
                    uploadPic(takePath)
                }
                RequestCodes.PICK_PHOTO -> {
                    if (data != null) {
                        val pickpath = Uri.parse(ImagePathUtil.getImageAbsolutePath(this, data.data))
                        uploadPic(pickpath)
                    }
                }
                RequestCodes.TAKE_BRAND -> {
                    if (data != null) {
                        et_band.setText(data.getStringExtra("brand"))
                        this.vehicleBrandUuid = data.getStringExtra("brandId")
                    }
                }
            }
        }

    }

    private fun uploadPic(photoUris: Uri) {
        builder = TipDialog.Builder(this)
        loadingDialog = builder
                .setIconType(TipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在上传").create()
        loadingDialog.show()
        val b = UriUtils.getPath(this, photoUris) == null

        mUploadHelper?.uploadPic(uploadListener, if (b) photoUris.path else UriUtils.getPath(this, photoUris))

    }


    private fun setResetState() {
        var bean = intent.getSerializableExtra(MainProtocol.KEY_BEAN)

        if (bean != null) {
            var lisenseBean = bean as LisenseBean
            addTitleBar(object : TitleWithAction("车主认证") {
                override fun onBindTitleBar(titleView: View?) {
                    super.onBindTitleBar(titleView)
                    var action = titleView?.findViewById<TextView>(R.id.tv_action)
                    when (lisenseBean.auditStatus) {
                        "1" -> {//审核通过
                            action?.setText("")
                            tv_reset_car_lisense.visibility = View.GONE
                            tv_reset_driver_lisense.visibility = View.GONE
                            tv_reset_car_pic.visibility = View.GONE
                        }
                        "2" -> {//审核拒绝
                            tv_reset_car_lisense.visibility = View.GONE
                            tv_reset_driver_lisense.visibility = View.GONE
                            tv_reset_car_pic.visibility = View.GONE
                            action?.setText("删除")
                        }
                        else -> {//审核中

                        }
                    }

                    action?.setCompoundDrawables(null, null, null, null)

                    action?.setOnClickListener {
                        deleteInfo(lisenseBean.uuid)
                    }
                }
            })
            carLisense = lisenseBean.travelCard
            driverLisense = lisenseBean.driveCard
            carPic = lisenseBean.vehiclePicture

            PicUtils.loadNormal(carLisense, iv_car_lisense)
            PicUtils.loadNormal(driverLisense, iv_driver_lisense)
            PicUtils.loadNormal(carPic, iv_car_pic)
            et_name.setText(lisenseBean.name)
            et_mobile.setText(lisenseBean.phone)
            //todo 型号文字
            et_band.setText(lisenseBean.brandName)
        } else {
            addTitleBar(object : TitleWithAction("车主认证") {
                override fun onBindTitleBar(titleView: View?) {
                    super.onBindTitleBar(titleView)
                    var action = titleView?.findViewById<TextView>(R.id.tv_action)

                    action?.setText("完成")

                    action?.setCompoundDrawables(null, null, null, null)

                    action?.setOnClickListener {
                        EventBus.getDefault().postSticky(MessageUpdateCarListEvent())
                        publish()
                    }
                }
            })
        }

        if (TextUtils.isEmpty(carLisense)) {
            tv_reset_car_lisense.visibility = View.INVISIBLE
        }
        if (TextUtils.isEmpty(driverLisense)) {
            tv_reset_driver_lisense.visibility = View.INVISIBLE
        }
        if (TextUtils.isEmpty(carPic)) {
            tv_reset_car_pic.visibility = View.INVISIBLE
        }

        tv_reset_car_lisense.setOnClickListener {
            selectPic(Constants.TYPE_CAR_LISENSE)

        }
        tv_reset_driver_lisense.setOnClickListener {
            selectPic(Constants.TYPE_DRIVER_LISENSE)

        }
        tv_reset_car_pic.setOnClickListener {
            selectPic(Constants.TYPE_CAR_PIC)
        }

        tv_band_choose.setOnClickListener {
            startActivityForResult(Intent(
                    this@VerifyDriverActivity, BrandActivity::class.java), RequestCodes.TAKE_BRAND)
        }
        tv_brand_choose_tow.setOnClickListener {
            startActivityForResult(Intent(
                    this@VerifyDriverActivity, BrandActivity::class.java), RequestCodes.TAKE_BRAND)
        }
    }

    lateinit var commonDialog: CommonDialog
    //删除认证消息
    private fun deleteInfo(uuid: String?) {
        val builder = CommonDialog.Builder(this)
        builder.setTitle("是否确认删除该信息？")

        builder.setNegativeButton("取消",
                resources.getColor(R.color.color14)) {
            commonDialog.dismiss()
        }

        builder.setPositiveButton("删除",
                resources.getColor(R.color.colorPrimary)) {
            CurrentServiceFactory
                    .delete_verify_info(uuid)
                    .subscribe(object : AbstractDialogSubscriber<ReasonBean>(this) {
                        override fun onNext(reasonBean: ReasonBean) {
                            ToastUtils.showShort(reasonBean.message)
                            EventBus.getDefault().postSticky(MessageUpdateCarListEvent())
                            finish()
                        }
                    })
            commonDialog.dismiss()
        }
        commonDialog = builder.create()
        commonDialog.show()
    }


    private fun selectPic(type: Int) {
        this.type = type

        var aliUIDisplayer: AliUIDisplayer
        when (type) {
            Constants.TYPE_CAR_LISENSE -> {
                aliUIDisplayer = AliUIDisplayer(iv_car_lisense, this, uploadListener)
            }
            Constants.TYPE_DRIVER_LISENSE -> {
                aliUIDisplayer = AliUIDisplayer(iv_driver_lisense, this, uploadListener)
            }
            else -> {
//                Constants.TYPE_CAR_PIC
                aliUIDisplayer = AliUIDisplayer(iv_car_pic, this, uploadListener)
            }
        }
        mUploadHelper = AliUploadHelper(this, aliUIDisplayer)

        camera?.checkPermission(CameraHandler(this))
    }

    private fun publish() {
        var name = et_name.text.toString()
        if (name.isNullOrEmpty()) {
            ToastUtils.showShort(et_name.hint)
            return
        }
        var mobile = et_mobile.text.toString()
        if (mobile.isNullOrEmpty()) {
            ToastUtils.showShort(et_mobile.hint)
            return
        }
        if (!StringUtil.isMobile(mobile)) {
            ToastUtils.showShort("请输入正确的手机号码")
            return
        }
        var brand = et_band.text.toString()
        if (brand.isNullOrEmpty()) {
            ToastUtils.showShort(et_band.hint)
            return
        }

        if (carLisense == null || driverLisense == null || carPic == null) {
            ToastUtils.showShort("请补充认证图片")
            return
        }
        var verifyCarBean = VerifyCarBean()
        verifyCarBean.name = name
        verifyCarBean.phone = mobile
        verifyCarBean.travelCard = carLisense
        verifyCarBean.driveCard = driverLisense
        verifyCarBean.vehiclePicture = carPic
        verifyCarBean.vehicleBrandUuid = vehicleBrandUuid
        verifyCarBean.vehicleTypeUuid = ""
        verifyCarBean.auditStatus = "0"

        UserServiceFactory.user_auth_vehicle(verifyCarBean)
                .subscribe(object : AbstractDialogSubscriber<UserInfoBean>(this) {
                    override fun onNext(t: UserInfoBean) {
                        var userResponseBody = UserResponseBody()
                        userResponseBody.token = DKUserManager.getUserToken()
                        userResponseBody.userInfo = t
                        DKUserManager.saveUserInfo(userResponseBody)
                        if (t.infoStatus.equals("3")) {
                            ToastUtils.showShort("审核失败，请重新检查资料")
                        } else {
                            postDelayedToFinish()
                        }
                    }
                })
    }

    override fun onBackPressed() {
        super.onBackPressed()
        mUploadHelper?.cancle()
    }
}
